package com.xiaomili.halfsugar.activity;


import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;


import com.xiaomili.halfsugar.R;
import com.xiaomili.halfsugar.fragment.SearchClickFragment;
import com.xiaomili.halfsugar.fragment.SearchHomePageFragment;

import java.util.ArrayList;
import java.util.List;

/**
 * 搜索的主页面
 * Created by Administrator on 2016/7/15.
 */
public class SearchActivity extends AppCompatActivity {
    private List<Fragment> mList;
    private FragmentTransaction mFragmentTransaction;
    private static final int HOMEPAGE = 0, CLICK = 1;
    private EditText et;
    private ImageView iv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        initView();
        initFragment();
        fragmentShow_Hide(mList.get(HOMEPAGE), mList.get(CLICK));
        viewListener(iv, et);

    }

    //初始化View
    private void initView() {
        et = (EditText) findViewById(R.id.search_toolbar_et);
        iv = (ImageView) findViewById(R.id.search_toolbar_iv);
    }

    //添加碎片
    private void initFragment() {
        mList = new ArrayList<>();
        mList.add(new SearchHomePageFragment());
        mList.add(new SearchClickFragment());
    }

    //碎片显示和隐藏
    private void fragmentShow_Hide(Fragment showfragment, Fragment hidefragment) {
        mFragmentTransaction = getSupportFragmentManager().beginTransaction();
        if (!(showfragment.isAdded() && hidefragment.isAdded())) {
            mFragmentTransaction.add(R.id.search_fragment, showfragment);
            mFragmentTransaction.add(R.id.search_fragment, hidefragment);
        }
        mFragmentTransaction.hide(hidefragment).show(showfragment).commit();

    }

    //控件的监听
    private void viewListener(ImageView iv, final EditText et) {
        iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                et.clearFocus();
                et.setText("");
                et.setHint("搜索的单品、清单、帖子、用户");
                finish();
            }
        });
        et.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                et.requestFocus();
            }
        });
        //        EditText或得焦点时的监听
        et.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    fragmentShow_Hide(mList.get(CLICK), mList.get(HOMEPAGE));
                } else {
                    fragmentShow_Hide(mList.get(HOMEPAGE), mList.get(CLICK));
                }
            }
        });

    }
}
